package com.aoxun.android.commons.impl;
/**
 * Created by Onelong on 2017/11/20.
 */
import android.os.Handler;
import android.os.Message;

import com.aoxun.android.commons.IMessageHandler;
import com.aoxun.android.commons.base.BaseActivity;

import java.lang.ref.WeakReference;

//这个还可以拆分
public class BaseMessageHandler implements IMessageHandler<Message> {
    /**
     *向其发消息，在undateU(msg)里面回调
     */
    public final MyHandler myHandler;

    public BaseMessageHandler(BaseActivity activity){
        myHandler = new MyHandler(activity);
    }
/*
    @Override
    public void postMessage(Message message) {
        if (message!=null){
            myHandler.sendMessage(message);
        }
    }
*/

    @Override
    public void sendMessage(Message message) {
        myHandler.sendMessage(message);
    }

    @Override
    public void post(Runnable r) {
        myHandler.post(r);
    }

    @Override
    public void postAtTime(Runnable r, long time) {
        myHandler.postAtTime(r, time);

    }

    @Override
    public void postDelayed(Runnable r, long time) {
        myHandler.postDelayed(r, time);
    }

    @Override
    public void sendEmptyMessage(int what) {
        myHandler.sendEmptyMessage(what);
    }

    @Override
    public void sendMessageAtTime(Message msg, long time) {
        myHandler.sendMessageAtTime(msg, time);
    }

    @Override
    public void sendMessageDelayed(Message msg, long time) {
        myHandler.sendMessageDelayed(msg, time);
    }

    @Override
    public void handleMessage(Message message) {
        //要Activity里面实现回调
        throw new RuntimeException("这个这里不能调用，要在本Activity里面实现回调");
    }


    @Override
    public void destory(){
        if(myHandler!=null){
            myHandler.removeCallbacksAndMessages(null);
            myHandler.mActivity.clear();
        }
        //myHandler = null;
    }



    /**
     * 处理内存泄漏
     */
    public static class MyHandler extends Handler {
        WeakReference<BaseActivity> mActivity;
        MyHandler(BaseActivity activity) {
            mActivity = new WeakReference<BaseActivity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            if (mActivity.get() != null && !mActivity.get().isFinishing()) {
                mActivity.get().handleMessage(msg);
            }
        }
    }


}
